import type { AdvancementInventoryChangedCriteria, CombinedAdvancementCriteria } from "@/types/advancement";
import useIcon from '@/hooks/useIcon'
import useItemUrl from "@/hooks/useItemUrl";

function getAFromIcon(id: string) {
  const { name, registerName } = useIcon(id)!
  return `<a href="${useItemUrl(id)}"}${registerName.replace("providencraft:", "")}">${name}</a>`
}

export function generateInventoryChanged(criterias: AdvancementInventoryChangedCriteria[]) {
  if (criterias.length === 1) {
    const items = criterias[0].conditions.items
    if (items.length === 1) {
      return `在物品栏中获得${getAFromIcon(items[0].item)}`
    }
    else {
      const res: string[] = []
      items.forEach(({ item }) => {
        res.push(`在物品栏中获得以下物品之一：${getAFromIcon(item)}`)
      })

      return res.join("、")
    }
  }
  else if (criterias.length > 1) {
    const res = "在物品栏中获得以下物品："
    const resArr: string[] = []
    criterias.forEach((criteria) => {
      const items = criteria.conditions.items
      if (items.length === 1) {
        resArr.push(`${getAFromIcon(items[0].item)}`)
      }
      else {
        const temp: string[] = []
        items.forEach(({ item }) => {
          temp.push(getAFromIcon(item))
        })
        resArr.push(`(其中之一：${temp.join("、")})`)
      }
    })
    return res + resArr.join("、")
  }

  return ""
}

export default function (criterias: Record<string, CombinedAdvancementCriteria>) {
  let res = ""
  const criteriaList = Object.values(criterias)
  const inventoryChangedList = criteriaList.filter(criteria => criteria.trigger === "minecraft:inventory_changed")

  res += generateInventoryChanged(inventoryChangedList)

  return res
}